'use strict'
const EventEmitter = require('events')
const net = require('net')
class Client extends EventEmitter {
  constructor (port, host, delay, keepAlive) {
    super()
    this.port = port
    this.host = host
    this.delay = delay
    this.keepAlive = keepAlive
  }
  _connect () {
    this.emit('onConnect')
    this.socket.on('timeout', this._timeout.bind(this))
    this.socket.on('error', this._error.bind(this))
    this.socket.on('close', this._close.bind(this))
    this.socket.on('data', this._data.bind(this))
    this.timer = setInterval(function () {
      this.keepAlive()
    }.bind(this), this.delay)
  }
  _timeout () {
    this.emit('onTimeout')
    clearInterval(this.timer)
    this.socket.destroy()
  }
  _error (e) {
    this.emit('onError')
    setTimeout(function () {
      this.start()
    }.bind(this), 5 * 1000)
  }
  _close () {
    clearInterval(this.timer)
    this.socket.isOpen = false
    this.emit('onClose')
  }
  _data (strHex) {
    this.emit('onData', strHex)
  }
  close () {
    clearInterval(this.timer)
    if (this.socket) {
      this.socket.destroy()
    }
  }
  start () {
    this.socket = new net.Socket()
    this.socket.isOpen = true
    this.socket.setEncoding('hex')
    this.socket.connect(this.port, this.host, this._connect.bind(this))
  }
  send (msg) {
    try {
      if (this.socket.isOpen) {
        this.socket.write(msg)
      }
    } catch (e) {

    } finally {

    }
  }

}
module.exports = Client
